extends CharacterBody2D

@onready var bulletPos: Node2D = $GunRotation/BulletSpawn
@onready var gun: Node2D = $GunRotation
@onready var synchronizer = $MultiplayerSynchronizer
@export var bullet: PackedScene

const SPEED = 300.0
const JUMP_VELOCITY = -400.0
# 获取项目设置的重力参数
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
# 待同步的数据
var syncPos = Vector2(0, 0)
var syncRot = 0

const LERP_SPEED = 5

func _ready() -> void:
	# 设置多人同步器——用于确定谁有控制的权限
	synchronizer.set_multiplayer_authority(name.to_int())

func _physics_process(delta) -> void:
	# 权限校验如果是其他玩家则直接同步数据
	if synchronizer.get_multiplayer_authority() != multiplayer.get_unique_id():
		global_position = global_position.lerp(syncPos, 0.1)
		gun.rotation_degrees = lerpf(gun.rotation_degrees, syncRot, 0.1)
		return
		
	# 重力效果
	if not is_on_floor():
		velocity.y += gravity * delta
	# 枪始终指向鼠标的位置
	gun.look_at(get_viewport().get_mouse_position())
	# 处理跳跃逻辑
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY
	
	# 如果是本地玩家，将数据同步到服务器
	syncPos = global_position
	syncRot = gun.rotation_degrees

	# 开火检测
	if Input.is_action_just_pressed("Fire"): fire.rpc()
	move()

# 移动
func move() -> void:
	var direction = Input.get_axis("ui_left", "ui_right")
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
	move_and_slide()

# 开枪
@rpc("any_peer", "call_local")
func fire() -> void:
	var b = bullet.instantiate()
	b.global_position = bulletPos.global_position
	b.rotation_degrees = gun.rotation_degrees
	get_tree().root.add_child(b)
